<template>
  <div class="home">
    <!-- 导航栏 -->
    <Navbar />
    
    <!-- 调试路由组件，方便开发和调试 -->
    <!-- <DebugRoutes /> -->
    
    <header class="header">
      <div class="search-box">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索歌曲、歌手、专辑..." 
          @keyup.enter="searchMusic"
        />
        <button @click="searchMusic">搜索</button>
      </div>
    </header>

    <div class="main-content">
      <div class="sidebar">
        <h2>推荐歌单</h2>
        <ul class="playlist-list">
          <li 
            v-for="playlist in recommendPlaylists" 
            :key="playlist.id"
            @click="loadPlaylistSongs(playlist.id)"
            :class="{ active: currentPlaylist === playlist.id }"
          >
            <img :src="playlist.picUrl" :alt="playlist.name" />
            <span>{{ playlist.name }}</span>
          </li>
        </ul>
      </div>

      <div class="content">
        <div v-if="loading" class="loading">加载中...</div>
        <div v-else-if="errorMessage" class="error">{{ errorMessage }}</div>
        <div v-else>
          <h2>{{ currentPlaylistName || '热门歌曲' }}</h2>
          <div class="table-container">
            <table class="song-table">
              <thead>
                <tr>
                  <th></th>
                  <th>歌曲</th>
                  <th>歌手</th>
                  <th>专辑</th>
                  <th>时长</th>
                </tr>
              </thead>
              <tbody>
                <tr 
                  v-for="(song, index) in songs" 
                  :key="song.id"
                  @click="playSong(song)"
                  :class="{ active: currentSong && currentSong.id === song.id }"
                >
                  <td>{{ index + 1 }}</td>
                  <td>{{ song.name }}</td>
                  <td>{{ song.ar ? song.ar.map(a => a.name).join(', ') : song.artists.map(a => a.name).join(', ') }}</td>
                  <td>{{ song.al ? song.al.name : song.album.name }}</td>
                  <td>{{ formatDuration(song.dt || song.duration) }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>

    <div class="player" v-if="currentSong">
      <div class="player-info">
        <img 
          :src="currentSong.al ? currentSong.al.picUrl : currentSong.album.picUrl" 
          :alt="currentSong.name" 
          @click="goToSongDetail"
          style="cursor: pointer;"
        />
        <div class="song-info">
          <h3>{{ currentSong.name }}</h3>
          <p>{{ currentSong.ar ? currentSong.ar.map(a => a.name).join(', ') : currentSong.artists.map(a => a.name).join(', ') }}</p>
        </div>
      </div>
      <div class="player-controls">
        <button @click="prevSong"><i class="icon">⏮</i></button>
        <button @click="togglePlay"><i class="icon">{{ isPlaying ? '⏸' : '▶' }}</i></button>
        <button @click="nextSong"><i class="icon">⏭</i></button>
      </div>
      <div class="player-progress">
        <span>{{ formatDuration(currentTime * 1000) }}</span>
        <input 
          type="range" 
          min="0" 
          :max="duration" 
          v-model="currentTime"
          @input="seek"
        />
        <span>{{ formatDuration(duration * 1000) }}</span>
      </div>
      <div class="player-volume">
        <i class="icon">🔊</i>
        <input 
          type="range" 
          min="0" 
          max="1" 
          step="0.01"
          v-model="volume"
          @input="setVolume"
        />
      </div>
    </div>

    <audio 
      ref="audioPlayer"
      @timeupdate="onTimeUpdate"
      @loadedmetadata="onLoadedMetadata"
      @ended="onEnded"
    ></audio>
  </div>
</template>

<script>
import Navbar from '../components/Navbar.vue';
import DebugRoutes from '../components/DebugRoutes.vue';

export default {
  name: 'Home',
  components: {
    Navbar,
    DebugRoutes
  },
  data() {
    return {
      searchQuery: '',
      songs: [],
      recommendPlaylists: [],
      currentPlaylist: null,
      currentPlaylistName: '',
      currentSong: null,
      isPlaying: false,
      currentTime: 0,
      duration: 0,
      volume: 0.7,
      loading: true,
      errorMessage: ''
    };
  },
  mounted() {
    // 组件挂载时获取推荐歌单和热门歌曲
    this.fetchRecommendPlaylists();
    this.fetchHotSongs();
    
    // 初始化音频播放器音量
    const audio = this.$refs.audioPlayer;
    audio.volume = this.volume;
  },
  methods: {
    // 获取推荐歌单数据
    async fetchRecommendPlaylists() {
      try {
        const response = await this.$http.get('/api/personalized?limit=10');
        
        // 检查API响应
        if (response.data.body.code === 200 && response.data.body.result) {
          this.recommendPlaylists = response.data.body.result;
        } else {
          this.recommendPlaylists = [];
          this.errorMessage = '获取推荐歌单失败';
        }
      } catch (error) {
        console.error('获取推荐歌单失败:', error);
        this.recommendPlaylists = [];
        this.errorMessage = '获取推荐歌单失败';
      }
    },
    // 获取热门歌曲数据
    async fetchHotSongs() {
      try {
        this.loading = true;
        // 首先获取排行榜列表
        const response = await this.$http.get('/topList');
        // const response = await this.$http.get('/api/toplist');
        // 然后获取第一个排行榜(网易云音乐热歌榜)的详细歌曲列表
        if (response.data.code === 200 && response.data.data && response.data.data.length > 0) {
          const topListId = response.data.data[0].id;
          const topListResponse = await this.$http.get(`/api/playlist_detail?id=${topListId}`);
          if (topListResponse.data.body.code === 200 && topListResponse.data.body.playlist) {
            this.songs = topListResponse.data.body.playlist.tracks.slice(0, 100);
            this.currentPlaylistName = topListResponse.data.body.playlist.name;
          }
        }
        this.loading = false;
      } catch (error) {
        console.error('获取热门歌曲失败:', error);
        this.errorMessage = '获取热门歌曲失败';
        this.loading = false;
      }
    },
    // 搜索音乐功能
    async searchMusic() {
      if (!this.searchQuery.trim()) return;
      
      try {
        this.loading = true;
        const response = await this.$http.get(`/api/search?keywords=${encodeURIComponent(this.searchQuery)}&limit=50`);
        
        // 检查API响应
        if (response.data.body.code === 200 && response.data.body.result && response.data.body.result.songs) {
          this.songs = response.data.body.result.songs;
          this.currentPlaylist = null;
          this.currentPlaylistName = `"${this.searchQuery}" 的搜索结果`;
        } else {
          this.songs = [];
          this.errorMessage = '未找到相关歌曲';
        }
        this.loading = false;
      } catch (error) {
        console.error('搜索音乐失败:', error);
        this.errorMessage = '搜索音乐失败';
        this.loading = false;
      }
    },
    // 加载歌单中的歌曲
    async loadPlaylistSongs(playlistId) {
      try {
        this.loading = true;
        this.currentPlaylist = playlistId;
        
        const response = await this.$http.get(`/api/playlist_detail?id=${playlistId}`);
        
        // 检查API响应
        if (response.data.body.code === 200 && response.data.body.playlist) {
          const playlist = response.data.body.playlist;
          this.currentPlaylistName = playlist.name;
          
          // 直接从歌单详情中获取歌曲信息，不需要再次请求song_detail
          this.songs = playlist.tracks.slice(0, 100);
        } else {
          this.songs = [];
          this.errorMessage = '加载歌单失败';
        }
        
        this.loading = false;
      } catch (error) {
        console.error('加载歌单失败:', error);
        this.errorMessage = '加载歌单失败';
        this.loading = false;
      }
    },
    // 播放指定歌曲
    async playSong(song) {
      try {
        // 获取歌曲URL
        const response = await this.$http.get(`/api/song_url?id=${song.id}`);
        
        // 检查API响应
        if (response.data.body.code === 200 && response.data.body.data && response.data.body.data.length > 0) {
          const songUrl = response.data.body.data[0].url;
          
          if (!songUrl) {
            this.errorMessage = '该歌曲无法播放';
            return;
          }
          
          this.currentSong = song;
          this.errorMessage = '';
          
          // 设置音频源并播放
          const audio = this.$refs.audioPlayer;
          audio.src = songUrl;
          
          try {
            await audio.play();
            this.isPlaying = true;
          } catch (playError) {
            // 处理自动播放限制
            console.warn('自动播放被浏览器阻止:', playError);
            this.isPlaying = false;
            this.errorMessage = '点击播放按钮开始播放';
          }
        } else {
          this.errorMessage = '获取歌曲资源失败';
        }
      } catch (error) {
        console.error('播放歌曲失败:', error);
        this.$t('search.playFailed')
      }
    },
    // 切换播放/暂停状态
    togglePlay() {
      const audio = this.$refs.audioPlayer;
      if (this.isPlaying) {
        audio.pause();
      } else {
        audio.play();
      }
      this.isPlaying = !this.isPlaying;
    },
    // 播放下一首歌曲
    nextSong() {
      const currentIndex = this.songs.findIndex(song => song.id === this.currentSong.id);
      if (currentIndex < this.songs.length - 1) {
        this.playSong(this.songs[currentIndex + 1]);
      }
    },
    // 播放上一首歌曲
    prevSong() {
      const currentIndex = this.songs.findIndex(song => song.id === this.currentSong.id);
      if (currentIndex > 0) {
        this.playSong(this.songs[currentIndex - 1]);
      }
    },
    
    // 跳转到歌曲详情页
    goToSongDetail() {
      if (this.currentSong) {
        this.$router.push(`/song/${this.currentSong.id}`);
        console.log(`/song/${this.currentSong.id}`,'跳转歌曲详情页')
      }
    },
    
    // 音频播放时间更新回调
    onTimeUpdate() {
      this.currentTime = this.$refs.audioPlayer.currentTime;
    },
    // 音频元数据加载完成回调
    onLoadedMetadata() {
      this.duration = this.$refs.audioPlayer.duration;
    },
    // 音频播放结束回调
    onEnded() {
      this.nextSong();
    },
    // 调整播放进度
    seek() {
      this.$refs.audioPlayer.currentTime = this.currentTime;
    },
    // 设置音量
    setVolume() {
      this.$refs.audioPlayer.volume = this.volume;
    },
    // 格式化时长（毫秒转分:秒）
    formatDuration(ms) {
      const minutes = Math.floor(ms / 60000);
      const seconds = Math.floor((ms % 60000) / 1000);
      return `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;
    }
  }
};
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  background-color: #f5f5f5;
  color: #333;
}

.home {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.header {
  background-color: #c20c0c;
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  display: flex;
  width: 300px;
}

.search-box input {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 4px 0 0 4px;
  outline: none;
}

.search-box button {
  padding: 8px 16px;
  background-color: #333;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.main-content {
  display: flex;
  height: calc(100vh - 180px);
  overflow: hidden;
}

.sidebar {
  width: 250px;
  background-color: #f2f2f2;
  padding: 20px;
  overflow-y: auto;
}

.playlist-list {
  list-style: none;
  margin-top: 15px;
}

.playlist-list li {
  display: flex;
  align-items: center;
  padding: 10px;
  cursor: pointer;
  border-radius: 4px;
  margin-bottom: 5px;
}

.playlist-list li:hover {
  background-color: #e6e6e6;
}

.playlist-list li.active {
  background-color: #e6e6e6;
}

.playlist-list li img {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  margin-right: 10px;
}

.content {
  flex: 1;
  padding: 20px;
}

.table-container {
  position: relative;
  height: calc(100vh - 240px);
  overflow-y: auto;
}

.song-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 15px;
}

.song-table tbody {
  height: auto;
  overflow-y: scroll;
}

.song-table th, .song-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.song-table th {
  font-weight: bold;
  color: #666;
}

.song-table tbody tr {
  cursor: pointer;
}

.song-table tbody tr:hover {
  background-color: #f9f9f9;
}

.song-table tbody tr.active {
  background-color: #e6f7ff;
}

.player {
  background-color: #fafafa;
  border-top: 1px solid #e0e0e0;
  padding: 15px 20px;
  display: flex;
  align-items: center;
}

.player-info {
  display: flex;
  align-items: center;
  width: 300px;
}

.player-info img {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 15px;
}

.song-info h3 {
  font-size: 16px;
  margin-bottom: 5px;
}

.song-info p {
  font-size: 14px;
  color: #666;
}

.player-controls {
  display: flex;
  align-items: center;
  margin: 0 20px;
}

.player-controls button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  margin: 0 10px;
  color: #333;
}

.player-progress {
  flex: 1;
  display: flex;
  align-items: center;
}

.player-progress input {
  flex: 1;
  margin: 0 10px;
}

.player-volume {
  display: flex;
  align-items: center;
  width: 150px;
  margin-left: 20px;
}

.player-volume input {
  flex: 1;
  margin-left: 10px;
}

.loading {
  text-align: center;
  padding: 40px;
  font-size: 18px;
  color: #999;
}

.error {
  text-align: center;
  padding: 40px;
  font-size: 18px;
  color: #c20c0c;
}

.icon {
  font-style: normal;
}

.icon {
  font-style: normal;
}
</style>